import { nextTick } from 'vue';

const PLACEHOLDER_IMAGE = 'https://goalgold.obs.ap-southeast-1.myhuaweicloud.com/banks/img-loading.png'; // 占位图片
const FALLBACK_IMAGE = 'https://goalgold.obs.ap-southeast-1.myhuaweicloud.com/banks/img-error.png'; // 加载错误图片
// 具体使用：
// <img v-lazy="'https://example.com/path/to/image.jpg'"
//        placeholder="https://example.com/path/to/placeholder.jpg"
//        fallback="https://example.com/path/to/fallback.jpg" />

const loadImage = (el: any, binding: any) => {
  const img = new Image();
  img.src = binding.value;

  img.onload = () => {
    el.src = binding.value;
  };

  img.onerror = () => {
    el.src = binding.instance.$attrs.fallback || FALLBACK_IMAGE;
  };
};

export default {
  beforeMount(el: any, binding: any) {
    el.dataset.src = binding.value;
    el.src = binding.instance.$attrs.placeholder || PLACEHOLDER_IMAGE;
  },
  mounted(el: any, binding: any, vnode: any) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          loadImage(el, binding);
          observer.unobserve(el);
        }
      });
    });

    nextTick(() => {
      observer.observe(el);
    });
  },
  beforeUpdate(el: any, binding: any) {
    if (binding.oldValue !== binding.value) {
      el.dataset.src = binding.value;
      el.src = binding.instance.$attrs.placeholder || PLACEHOLDER_IMAGE;
    }
  },
  updated(el: any, binding: any) {
    if (binding.oldValue !== binding.value) {
      loadImage(el, binding);
    }
  },
};
